<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 顶部 -->

      <page-tools :is-show-warning="true">
        <!-- 左边部门 -->
        <template v-slot:before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <!-- 右边部门 按钮 -->
        <!-- <template v-slot:after> -->
        <template slot="after">
          <el-button type="success" @click="$router.push('/import')">导入</el-button>
          <el-button type="danger" @click="exportFn">导出</el-button>
          <el-button type="primary" :disabled="!checkPermission('add-employee')" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="loading">
        <!-- 表格 -->
        <el-table label-width="120px" :data="employeeData">
          <el-table-column align="center" header-align="center" label="序号" type="index" />
          <el-table-column align="center" header-align="center" label="姓名" :sortable="true" prop="username" />
          <el-table-column align="center" header-align="center" label="头像" prop="staffPhoto" width="120">
            <template slot-scope="{row}">
              <img
                v-imagerror="require('@/assets/common/jmq3.png')"
                :src="row.staffPhoto"
                alt=""
                style="width: 100px; height: 100px; border-radius: 50%"
                @click="showQrCode(row.staffPhoto)"
              >
              <el-dialog :visible.sync="showPhoto">
                <canvas ref="myCanvas" />
              </el-dialog>
            </template>
          </el-table-column>
          <el-table-column align="center" header-align="center" label="手机号" width="120px" prop="mobile" />
          <el-table-column align="center" header-align="center" label="工号" :sortable="true" prop="workNumber" />

          <el-table-column
            align="center"
            header-align="center"
            label="聘用形式"
            :sortable="true"
            prop="formOfEmployment"
            :formatter="formOfEmployment"
          />

          <el-table-column align="center" header-align="center" label="部门" :sortable="true" prop="departmentName" />

          <el-table-column align="center" header-align="center" label="入职时间" width="120px">
            <!-- slot或者v-slot【后者要写在template上面】是对应名字 slot标签的name值
            v-slot:name="变量值"
            slot-scoped对应的是作用域插槽，用一个变量能够接受传递来的值 -->
            <template slot-scope="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            header-align="center"
            width="120px"
            :sortable="true"
            label="转正时间"
            prop="correctionTime"
          >
            <template slot-scope="{row}">
              {{ row.correctionTime | formatDate }}
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            header-align="center"
            label="账户状态"
            :sortable="true"
          >
            <template>
              <el-switch v-model="enableState" />
            </template>
          </el-table-column>
          <!-- 文字按钮 没有边框和背景色的按钮 -->
          <el-table-column

            label="操作"
            :sortable="true"
            align="center"
            header-align="center"
            width="250"
          >
            <template slot-scope="{row}">
              <el-button :disabled="!checkPermission('check-employee')" type="text" size="mini" @click="$router.push(`/employees/details/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini">转正</el-button>
              <el-button type="text" size="mini">调岗</el-button>
              <el-button type="text" size="mini">离职</el-button>
              <el-button type="text" size="mini" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="mini" :disabled="!checkPermission('del-employees')" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-row type="flex" justify="center" style="height: 80px" align="middle">
          <el-col :span="4">
            <el-pagination
              layout="prev, pager,next"
              :page-size="page.size"
              :total="page.total"
              :current-page="page.page"
              @current-change="changePage"
            />
          </el-col>
        </el-row>
      </el-card>
      <add-employ :show-dialog.sync="showDialog" />
      <assign-role ref="myRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>>

<script>
import { getEmployeeMultipleAPI, deleteEmployeeAPI } from '@/api'
import employees from '@/api/constant/employees'
import AddEmploy from './component/add-employ'
// 引入编辑角色组件
import AssignRole from './component/assign-role'
// 时间过滤器
import { formatDate } from '@/filters/index'
// 引入二维码组件
import QrCode from 'qrcode'

export default {
  components: {
    AddEmploy,
    AssignRole
  },
  data() {
    return {
      page: {
        page: 1, // 当前页码
        size: 2, // 每页的条数
        total: 0 // 总页数
      },
      // 承接返回的数据
      employeeData: [],
      loading: false, // 加载状态
      enableState: true, // 账户状态
      showDialog: false, // 增加用户 显示弹层
      showPhoto: false, // 头像弹层设置
      showRoleDialog: false, // 编辑角色弹层
      userId: null // 当前用户的id 角色用
    }
  },
  created() {
    this.getEmployeeMultiple()
  },
  methods: {
    // 获取所有的员工信息
    async getEmployeeMultiple() {
      this.loading = true
      const { rows, total } = await getEmployeeMultipleAPI(this.page)
      console.log(rows)
      this.page.total = total
      // 员工信息 用变量存储 给table遍历
      this.employeeData = rows
      this.loading = false
    },
    // 分页函数
    changePage(page) {
      // page对象里面的page字段等于当前页 当前页是监听事件current-change调用函数 传入进来的
      this.page.page = page
      // 重新获取页面数据
      this.getEmployeeMultiple()
    },
    // 格式化聘用形式
    formOfEmployment(row, col, cellValue) {
      const obj = employees.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '暂不明确'
    },
    // 删除员工信息
    async deleteEmployee(id) {
      try {
        await this.$confirm('确认要删除吗?')
        const res = await deleteEmployeeAPI(id)
        console.log(res)
        // 重新获取员工信息
        this.getEmployeeMultiple()
        // 提示消息
        this.message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },

    // 导出Excel 懒加载
    exportFn() {
      import('@/vendor/Export2Excel').then(async excel => {
        const headers = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const { rows } = await getEmployeeMultipleAPI({
          page: 1,
          size: this.page.total
        })
        console.log(rows)
        const data = this.formatJson(rows, headers)
        const multiHeader = [['姓名', '', '', '', '', '', '部门'], [
          '帅哥', '', '', '', '', '', ''
        ]]
        const merges = []
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data: data,
          filename: '员工信息',
          multiHeader: multiHeader,
          merges: merges
        })
      })

      // data 目标[{name: '张三','mobile': '13333333333'},{name: '张三','mobile': '13333333333'}] => 转化为 [[张三,13333333333],[张三,13333333333]]
      // 数据和header对应顺序
      // 英文 转化为 中文
    },
    // 转化日期 数字为 字符
    formatJson(rows, headers) {
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'formOfEmployment') {
            const obj = employees.hireType.find(obj => obj.id === item[headers[key]])
            // 如果是formOfEmployment 且id是1 值return就是 obj.value
            return obj ? obj.value : '暂不明确'
          } else if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            console.log(item[headers[key]])

            return formatDate(item[headers[key]], 'yyyy-mm-dd')
          }
          return item[headers[key]]
        })
      })
    },

    // 显示二维码
    showQrCode(url) {
      if (url) {
        this.showPhoto = true // 显示弹层
        // 数据更新了 弹层不会立刻出现 因为页面的渲染是异步的
        // 一个方法 在上次数据更新完毕 页面渲染完毕 再执行
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('当前没有上传头像')
      }
    },

    // 编辑角色
    async editRole(id) {
      this.userId = id
      await this.$refs.myRole.getUserDetailInfo(id)
      this.showRoleDialog = true
    }
  }

}
</script>

<style>

</style>
